package com.iwayin.core.dao.setting;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.iwayin.core.dao.BaseDAOImpl;
import com.iwayin.core.dataobject.EmailSettingDO;

public class EmailSettingDAOImpl extends BaseDAOImpl implements EmailSettingDAO {
	
	private LoadingCache<String, EmailSettingDO> esCache = CacheBuilder.newBuilder()
			.expireAfterAccess(3600*24, TimeUnit.SECONDS).maximumSize(10000)
			.build(new CacheLoader<String, EmailSettingDO>(){
				@Override
				public EmailSettingDO load(String key) throws Exception {
					logger.debug("Read EmailSetting From DB====================");
					String[] strs = key.split("_");
					EmailSettingDO es =  (EmailSettingDO) queryForObject("EmailSettingDAO.getEmailSettingDO", Long.valueOf(strs[1]));
					if(es == null)
						es = new EmailSettingDO();
					return es;
				}
			});

	@Override
	public void createEmailSetting(EmailSettingDO es) {
		this.executeInsert("EmailSettingDAO.createEmailSetting", es);

	}

	@Override
	public Integer updateEmailSetting(EmailSettingDO es) {
		Integer i = this.executeUpdate("EmailSettingDAO.updateEmailSetting", es);
		remove(es.getUserId());
		return i;
	}

	@Override
	public EmailSettingDO getEmailSettingDO(Long userId) {
		EmailSettingDO es =  get(userId);
		if (es != null && es.getUserId() == null) {
			remove(userId);
			return null;
		}
		return es;
	}
	
	private EmailSettingDO get(Long userId){
		try {
			return esCache.get("UEMAILSETTING_"+userId);
		} catch (ExecutionException e) {
			return null;
		}
	}
	
	private void remove(Long userId){
		esCache.invalidate("UEMAILSETTING_"+userId);
	}
}
